package com.dkd.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.dkd.sbtz.domain.AssetAssessment;
import com.dkd.sbtz.domain.AssetMtplan;
import com.dkd.sbtz.mapper.AssetAssessmentMapper;
import com.dkd.sbtz.mapper.AssetMtplanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component("assetPlanGenTask")
public class AssetPlanGenTask {

    @Autowired
    private AssetAssessmentMapper assessmentMapper;

    @Autowired
    private AssetMtplanMapper mtplanMapper;

    private LocalDate toLocalDate(Date date) {
        if (date == null) {
            return LocalDate.now();
        }
        return date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 自动生成一年的维护计划
     */
    public void generateYearPlan() {
        List<AssetAssessment> list = assessmentMapper.selectAllValid();
        System.out.println("找到设备评估数量: " + list.size());

        for (AssetAssessment a : list) {
            int monthCycle = getCycleByLevel(a.getCriticalLevel());
            if (monthCycle == 0) continue;

            // 维护工种：优先解析 JSON 数组，若失败则回退到逗号分隔
            List<String> trades = parseMaintainType(a.getMaintainType());
            if (trades.isEmpty()) {
                // 如果没有维护工种，仍然生成一条默认记录（可按需求调整）
                trades.add("");
            }

            LocalDate start = toLocalDate(a.getInitialDate());
            for (String trade : trades) {
                // 去掉两端空白
                String tradeCode = trade == null ? "" : trade.trim();

                for (int i = 0; i < 12; i += monthCycle) {
                    LocalDate planDate = start.plusMonths(i);
                    if (planDate.isAfter(start.plus(1, ChronoUnit.YEARS))) break;

                    AssetMtplan plan = new AssetMtplan();
                    plan.setAssetId(a.getAssetId());
                    plan.setAssetmentId(a.getId());
                    plan.setTitle("年度维护计划-" + a.getCriticalLevel());
                    plan.setPlanDate(java.sql.Date.valueOf(planDate));
                    plan.setPlanHour(0);
                    plan.setPlanContent(a.getPlanContent());
                    plan.setSpareType(a.getIsSpecial());
                    plan.setNeedSpare(1);
                    plan.setTradeCode(tradeCode); // tradeCode 可为空或数字/字符串
                    plan.setPriority(getPriorityByLevel(a.getCriticalLevel()));
                    plan.setPlanType("PM");
                    plan.setCycleType("MONTH");
                    // 如果实体的 cycleValue 是 Long，传入 Long
                    plan.setCycleValue(monthCycle);
                    plan.setGenPolicy("AUTO");
                    plan.setStatus("OPEN");
                    plan.setRemark("系统自动生成");
                    plan.setCreateBy("system");
                    plan.setCreateTime(new Date());
                    plan.setIsDelete(0);
                    plan.setParentAssetId(a.getParentAssetId());

                    mtplanMapper.insertAssetMtplanTmp(plan);
                }
            }
        }
        System.out.println("维护计划生成完成 ✅");
    }

    /**
     * 解析 maintainType 字段，兼容 JSON 数组与逗号分隔字符串
     */
    private List<String> parseMaintainType(String raw) {
        List<String> result = new ArrayList<>();
        if (raw == null) return result;

        String trimmed = raw.trim();
        if (trimmed.isEmpty()) return result;

        // 如果看起来像 JSON 数组（以 [ 开头，以 ] 结尾），尝试用 fastjson2 解析
        if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
            try {
                // 可能是数字数组或字符串数组，统一解析为 String 列表
                List<Object> arr = JSON.parseArray(trimmed, Object.class);
                for (Object o : arr) {
                    if (o != null) result.add(String.valueOf(o));
                }
                return result;
            } catch (Exception e) {
                // 解析失败，回退到逗号分隔策略
            }
        }

        // 回退：当做逗号分隔列表
        String[] parts = trimmed.split(",");
        for (String p : parts) {
            String t = p == null ? "" : p.trim();
            if (!t.isEmpty()) result.add(t);
        }
        return result;
    }

    private int getCycleByLevel(String level) {
        if ("A".equalsIgnoreCase(level)) return 1;
        if ("B".equalsIgnoreCase(level)) return 2;
        if ("C".equalsIgnoreCase(level)) return 3;
        return 0;
    }

    private String getPriorityByLevel(String level) {
        if ("A".equalsIgnoreCase(level)) return "HIGH";
        if ("B".equalsIgnoreCase(level)) return "MEDIUM";
        return "LOW";
    }
}
